<template>
  <div class="static-files-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-left">
          <h1 class="page-title">静态文件管理</h1>
          <p class="page-description">管理和查看生成的静态文件</p>
        </div>
        <div class="header-actions">
          <el-select
            v-model="searchForm.siteId"
            placeholder="选择站点"
            @change="onSiteChange"
            style="width: 200px; margin-right: 10px;"
          >
            <el-option
              v-for="site in sites"
              :key="site.id"
              :label="site.name"
              :value="site.id"
            />
          </el-select>
          <el-button @click="testTimeFormat" type="warning" style="margin-right: 10px;">
            测试时间格式化
          </el-button>
          <el-button @click="refreshFiles" :loading="loading" icon="Refresh">
            刷新
          </el-button>
          <el-button @click="exportReport" :loading="exporting" icon="Download">
            导出报告
          </el-button>
        </div>
      </div>
    </div>

    <!-- 统计概览 -->
    <div class="statistics-overview">
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-number">{{ statistics.totalFiles || 0 }}</div>
            <div class="stat-label">文件总数</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-number">{{ statistics.totalSize || '0 B' }}</div>
            <div class="stat-label">总大小</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-number">{{ statistics.htmlFiles || 0 }}</div>
            <div class="stat-label">HTML文件</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-number">{{ statistics.xmlFiles || 0 }}</div>
            <div class="stat-label">XML文件</div>
          </div>
        </el-col>
      </el-row>

      <!-- 最后生成时间单独显示 -->
      <div class="last-generated-info">
        <el-tag type="info" size="large">
          <el-icon><Clock /></el-icon>
          最后生成时间: {{ statistics.lastGenerated || '未生成' }}
        </el-tag>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="站点">
          <el-select v-model="searchForm.siteId" placeholder="选择站点" clearable @change="loadFiles">
            <el-option
              v-for="site in sites"
              :key="site.id"
              :label="site.name"
              :value="site.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="文件类型">
          <el-select v-model="searchForm.fileType" placeholder="选择类型" clearable @change="loadFiles">
            <el-option label="HTML文件" value="html" />
            <el-option label="XML文件" value="xml" />
            <el-option label="所有文件" value="" />
          </el-select>
        </el-form-item>
        <el-form-item label="文件名">
          <el-input
            v-model="searchForm.fileName"
            placeholder="输入文件名"
            clearable
            @keyup.enter="loadFiles"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadFiles" icon="Search">
            搜索
          </el-button>
          <el-button @click="resetSearch" icon="Refresh">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 文件列表 -->
    <el-card class="files-card">
      <template #header>
        <div class="card-header">
          <span>静态文件列表</span>
          <div class="header-actions">
            <el-button-group>
              <el-button
                :type="viewMode === 'table' ? 'primary' : 'default'"
                @click="viewMode = 'table'"
                icon="List"
                size="small"
              >
                列表
              </el-button>
              <el-button
                :type="viewMode === 'grid' ? 'primary' : 'default'"
                @click="viewMode = 'grid'"
                icon="Grid"
                size="small"
              >
                网格
              </el-button>
            </el-button-group>
          </div>
        </div>
      </template>

      <!-- 表格视图 -->
      <div v-if="viewMode === 'table'">
        <el-table :data="fileList" v-loading="loading" stripe>
          <el-table-column prop="name" label="文件名" min-width="200">
            <template #default="{ row }">
              <div class="file-name">
                <el-icon class="file-icon">
                  <Document v-if="row.type === 'html'" />
                  <Folder v-else />
                </el-icon>
                <span>{{ row.name }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="path" label="路径" min-width="300" show-overflow-tooltip />
          <el-table-column prop="size" label="大小" width="100" />
          <el-table-column prop="type" label="类型" width="80">
            <template #default="{ row }">
              <el-tag size="small" :type="getFileTypeColor(row.type)">
                {{ row.type.toUpperCase() }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="lastModified" label="修改时间" width="180" />
          <el-table-column label="操作" width="200" align="center">
            <template #default="{ row }">
              <el-button-group>
                <el-button type="primary" size="small" @click="previewFile(row)" icon="View">
                  预览
                </el-button>
                <el-button type="success" size="small" @click="downloadFile(row)" icon="Download">
                  下载
                </el-button>
                <el-button type="danger" size="small" @click="deleteFile(row)" icon="Delete">
                  删除
                </el-button>
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 网格视图 -->
      <div v-else class="grid-view">
        <div class="file-grid">
          <div
            v-for="file in fileList"
            :key="file.path"
            class="file-card"
            @click="previewFile(file)"
          >
            <div class="file-icon-large">
              <el-icon size="48">
                <Document v-if="file.type === 'html'" />
                <Folder v-else />
              </el-icon>
            </div>
            <div class="file-info">
              <div class="file-name" :title="file.name">{{ file.name }}</div>
              <div class="file-meta">
                <span class="file-size">{{ file.size }}</span>
                <span class="file-type">{{ file.type.toUpperCase() }}</span>
              </div>
            </div>
            <div class="file-actions">
              <el-button-group>
                <el-button type="primary" size="small" @click.stop="previewFile(file)" icon="View" />
                <el-button type="success" size="small" @click.stop="downloadFile(file)" icon="Download" />
                <el-button type="danger" size="small" @click.stop="deleteFile(file)" icon="Delete" />
              </el-button-group>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadFiles"
          @current-change="loadFiles"
        />
      </div>
    </el-card>

    <!-- 预览对话框 -->
    <el-dialog
      v-model="previewVisible"
      :title="`预览 - ${currentFile?.name}`"
      width="80%"
      top="5vh"
    >
      <div class="preview-content">
        <iframe
          v-if="currentFile?.type === 'html'"
          :src="currentFile.url"
          style="width: 100%; height: 600px; border: none;"
        />
        <pre v-else class="code-preview">{{ previewContent }}</pre>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Document, Folder, Clock } from '@element-plus/icons-vue'
import { staticFileApi } from '@/api/static-file'
import { siteApi } from '@/api/site'

// 响应式数据
const loading = ref(false)
const exporting = ref(false)
const viewMode = ref<'table' | 'grid'>('table')
const previewVisible = ref(false)
const currentFile = ref<any>(null)
const previewContent = ref('')

// 搜索表单
const searchForm = reactive({
  siteId: 1 as number | undefined, // 默认选择站点1
  fileType: '',
  fileName: ''
})

// 分页
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 数据
const sites = ref<any[]>([])
const fileList = ref<any[]>([])
const statistics = ref({
  totalFiles: 0,
  totalSize: '0 B',
  htmlFiles: 0,
  xmlFiles: 0,
  otherFiles: 0,
  lastGenerated: '未生成'
})

// 方法
const refreshFiles = async () => {
  await loadFiles()
  await loadStatistics()
  ElMessage.success('刷新成功')
}

const loadSites = async () => {
  try {
    const response = await siteApi.getList({ page: 1, size: 100 })
    if (response.code === 0) {
      sites.value = response.data?.records || response.data?.list || []
    }
  } catch (error) {
    console.error('加载站点失败:', error)
  }
}

const loadFiles = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      size: pagination.size,
      ...searchForm
    }
    
    const response = await staticFileApi.getFileList(params)
    if (response.code === 0) {
      fileList.value = response.data?.records || response.data?.list || []
      pagination.total = response.data?.total || 0
    } else {
      ElMessage.error(response.msg || '加载文件列表失败')
    }
  } catch (error) {
    console.error('加载文件列表失败:', error)
    ElMessage.error('加载文件列表失败')
  } finally {
    loading.value = false
  }
}

const loadStatistics = async () => {
  try {
    // 使用生成管理的统计接口，因为它返回正确的数据格式
    const siteId = searchForm.siteId || 1
    const response = await fetch(`/cms/admin/generate/statistics/${siteId}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': localStorage.getItem('token') || ''
      }
    })

    const result = await response.json()
    console.log('统计信息响应:', result)

    if (result.code === 0) {
      const data = result.data
      console.log('统计信息数据:', data)

      // 先格式化时间
      const formattedTime = formatDateTime(data.lastGenerated)
      console.log('格式化后的时间:', formattedTime)

      // 使用 Object.assign 确保响应式更新
      Object.assign(statistics.value, {
        totalFiles: parseInt(data.totalFiles) || 0,
        totalSize: data.totalSize || '0 B',
        htmlFiles: parseInt(data.htmlFiles) || 0,
        xmlFiles: parseInt(data.xmlFiles) || 0,
        otherFiles: parseInt(data.otherFiles) || 0,
        lastGenerated: formattedTime
      })

      console.log('处理后的统计信息:', statistics.value)

      // 强制触发响应式更新
      statistics.value = { ...statistics.value }
    } else {
      console.error('获取统计信息失败:', result.msg)
    }
  } catch (error) {
    console.error('加载统计信息失败:', error)
  }
}

const resetSearch = () => {
  Object.assign(searchForm, {
    siteId: undefined,
    fileType: '',
    fileName: ''
  })
  pagination.page = 1
  loadFiles()
}

const getFileTypeColor = (type: string) => {
  switch (type) {
    case 'html': return 'success'
    case 'xml': return 'warning'
    default: return 'info'
  }
}

// 格式化日期时间
const formatDateTime = (dateTimeStr: string) => {
  console.log('格式化时间输入:', dateTimeStr)

  if (!dateTimeStr || dateTimeStr === '未生成') {
    return '未生成'
  }

  try {
    // 处理 ISO 8601 格式的时间字符串
    let date = new Date(dateTimeStr)

    if (isNaN(date.getTime())) {
      console.warn('无法解析日期:', dateTimeStr)
      return '未生成' // 如果无法解析，返回未生成
    }

    // 转换为本地时间
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')

    const formatted = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    console.log('格式化时间输出:', formatted)

    return formatted
  } catch (error) {
    console.error('日期格式化失败:', error, '原始值:', dateTimeStr)
    return '未生成'
  }
}

const previewFile = async (file: any) => {
  currentFile.value = file
  
  if (file.type === 'html') {
    previewVisible.value = true
  } else {
    try {
      const response = await staticFileApi.getFileContent(file.path)
      if (response.code === 0) {
        previewContent.value = response.data
        previewVisible.value = true
      } else {
        ElMessage.error('获取文件内容失败')
      }
    } catch (error) {
      ElMessage.error('获取文件内容失败')
    }
  }
}

const downloadFile = (file: any) => {
  const link = document.createElement('a')
  link.href = file.url
  link.download = file.name
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

const deleteFile = async (file: any) => {
  try {
    await ElMessageBox.confirm(`确定要删除文件 "${file.name}" 吗？`, '确认删除', {
      type: 'warning'
    })
    
    const response = await staticFileApi.deleteFile(file.path)
    if (response.code === 0) {
      ElMessage.success('删除成功')
      await loadFiles()
      await loadStatistics()
    } else {
      ElMessage.error(response.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const exportReport = async () => {
  exporting.value = true
  try {
    const response = await staticFileApi.exportReport(searchForm.siteId)
    
    // 创建下载链接
    const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `静态文件报告_${new Date().toISOString().split('T')[0]}.xlsx`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('报告导出成功')
  } catch (error) {
    console.error('导出报告失败:', error)
    ElMessage.error('导出报告失败')
  } finally {
    exporting.value = false
  }
}

// 站点切换处理
const onSiteChange = async (siteId: number) => {
  console.log('切换站点:', siteId)
  searchForm.siteId = siteId
  // 重新加载文件列表和统计信息
  await Promise.all([loadFiles(), loadStatistics()])
}

// 测试时间格式化
const testTimeFormat = () => {
  const testTime = "2025-07-29T12:03:31.6931377Z"
  const formatted = formatDateTime(testTime)
  console.log('测试时间格式化:')
  console.log('输入:', testTime)
  console.log('输出:', formatted)

  ElMessage.success(`时间格式化测试: ${formatted}`)

  // 强制更新统计信息
  statistics.value.lastGenerated = formatted
}

// 页面加载
onMounted(() => {
  loadSites()
  loadFiles()
  loadStatistics()
})
</script>

<style scoped>
.static-files-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.page-description {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.statistics-overview {
  margin-bottom: 20px;
}

.stat-card {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  text-align: center;
}

.stat-number {
  font-size: 28px;
  font-weight: 600;
  color: #409eff;
  margin-bottom: 8px;
}

.stat-label {
  color: #909399;
  font-size: 14px;
}

.last-generated-info {
  margin-top: 15px;
  text-align: center;
}

.last-generated-info .el-tag {
  padding: 8px 16px;
  font-size: 14px;
}

.last-generated-info .el-icon {
  margin-right: 5px;
}

.search-card {
  margin-bottom: 20px;
}

.files-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.file-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

.file-icon {
  color: #409eff;
}

.grid-view {
  min-height: 400px;
}

.file-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
}

.file-card {
  border: 1px solid #ebeef5;
  border-radius: 8px;
  padding: 16px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
}

.file-card:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
}

.file-icon-large {
  margin-bottom: 12px;
  color: #409eff;
}

.file-info {
  margin-bottom: 12px;
}

.file-name {
  font-weight: 500;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file-meta {
  font-size: 12px;
  color: #909399;
  display: flex;
  justify-content: space-between;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.preview-content {
  max-height: 600px;
  overflow-y: auto;
}

.code-preview {
  background: #f5f7fa;
  padding: 16px;
  border-radius: 4px;
  font-family: 'Courier New', monospace;
  font-size: 12px;
  line-height: 1.5;
  white-space: pre-wrap;
  word-wrap: break-word;
}
</style>
